package com.zhong.oss.utils;

import com.zhong.oss.entity.FileInfo;
import io.minio.*;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * minio文件操作工具
 */
@Component
public class MinioUntil {

    @Resource
    private MinioClient minioClient;

    /**
     * 创建bucket
     */
    public void createBucket(String bucket) throws Exception {
        boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!exists) {
            //bucket不存在时则创建
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
    }

    /**
     * 上传文件
     */
    public void uploadFile(InputStream inputStream, String bucket, String objectName) throws Exception {
        minioClient.putObject(PutObjectArgs
                .builder()
                .bucket(bucket)
                .object(objectName)
                .stream(inputStream, -1, Integer.MAX_VALUE)
                .build());
    }


    /**
     * 列出所有桶
     */
    public List<String> getBucketAll() throws Exception{
        List<Bucket> bucketList = minioClient.listBuckets();
        return bucketList.stream().map(Bucket::name).collect(Collectors.toList());
    }

    /**
     * 列出指定桶内的所有文件
     */
    public List<FileInfo> getFileAll(String bucket) throws Exception{
        Iterable<Result<Item>> resultList = minioClient.listObjects(ListObjectsArgs.builder().bucket(bucket).build());
        List<FileInfo>  fileInfoList = new LinkedList<>();
        for (Result<Item> result : resultList) {
            FileInfo fileInfo = new FileInfo();
            Item item = result.get();

            fileInfo.setFileName(item.objectName());
            fileInfo.setEtag(item.etag());
            fileInfo.setDirectoryFlag(item.isDir());

            fileInfoList.add(fileInfo);
        }
        return fileInfoList;
    }

    /**
     * 下载文件
     */
    public InputStream downLoad(String bucket,String objectName) throws Exception{
        return minioClient.getObject(GetObjectArgs.builder().bucket(bucket).object(objectName).build());
    }

    /**
     * 删除桶
     */
    public void deleteBucket(String bucket) throws Exception{
        minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucket).build());
    }

    /**
     * 删除文件
     */
    public void deleteObject(String bucket,String objectName) throws Exception{
        minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucket).bucket(objectName).build());
    }

}
